package org.xiaozhiying;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.xiaozhiying.entity.CityWeatherEntity;
import org.xiaozhiying.enumrate.CityWeatherEnum;
import org.xiaozhiying.utils.DataBaseUtil;
import org.xiaozhiying.utils.HttpClientUtil;
import org.xiaozhiying.utils.JsonUtil;

import java.util.LinkedList;
import java.util.List;

public class App 
{
    // 作为程序的入口
    public static void main(String[] args) {
        String result = null;
        CityWeatherEntity cityWeatherEntity = null;
        // 如果有城市编号这个唯一参数，则只需要保存这个编号对应的城市天气信息，如果没有，则查询湖南所有城市的天气信息并保存
       if (args.length == 0) {
            // 保存湖南所有城市的天气信息
            List<String> urlList = CityWeatherEnum.getAllUrl();
            List<CityWeatherEntity> cityWeatherEntities = new LinkedList<>();
            for (String url : urlList) {
                result = HttpClientUtil.doGet(url);
                cityWeatherEntity = JsonUtil.parseJsonToObject(result);
                cityWeatherEntities.add(cityWeatherEntity);
            }
            // 保存入库
            DataBaseUtil.saveAllCitysWeatherInfo(cityWeatherEntities);
        } else {
            String cityCode = args[0];
            String url = CityWeatherEnum.getUrl(Integer.parseInt(cityCode));
            if (url != null) {
                result = HttpClientUtil.doGet(url);
            }
            cityWeatherEntity = JsonUtil.parseJsonToObject(result);
            // 保存入库
            DataBaseUtil.saveSingleCityWeatherInfo(cityWeatherEntity);
        }

        System.out.println( "over!" );
    }
}
